<template >
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <!-- 点击首页会跳转到home -->
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片试图区 -->
    <el-card class="box-card">
      <!-- 因为下面Tabs里面的V-model是字符串，所以data里index也是字符串，而这里是要数值，只能通过 index-0 实现 -->
      <el-alert title="添加商品的信息" center show-icon :closable="false"></el-alert>
      <el-steps :active="index-0" finish-status="success" class="Step">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 因为el-tabs和tab-pane不能分离开来，所以要包含在el-form里 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="0px"
        label-position="top"
      >
        <el-tabs
          v-model="index"
          :tab-position="'left'"
          :before-leave="beforeleavetab"
          @tab-click="tabClick"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input type="number" v-model="addForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input type="number" v-model="addForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input type="number" v-model="addForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addForm.goods_cat"
                :options="cateList"
                :props="addProps"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item :label="item.attr_name" v-for="item in manyData" :key="item.attr_id">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  class="checkbox"
                  border
                  :label="cb"
                  v-for="(cb,i) in item.attr_vals"
                  :key="i"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="item in onlyData" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- 图片上传 -->
            <el-upload
              class="upload-demo"
              action="http://127.0.0.1:8888/api/private/v1/upload"
              :on-success="uploadSuccess"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :headers="axiosToken"
              list-type="picture"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本 -->
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <button @click="addGoods">添加</button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 放大图片窗口 -->
    <el-dialog title="图片预览" :visible.sync="dialogVisiblePreview" width="50%">
      <img class="imgWidth" :src="urlPath" alt />
    </el-dialog>
  </div>
</template>

<script>
import _ from "lodash";

export default {
  data() {
    return {
      index: "0",
      // 基本信息表单数据对象
      addForm: {
        goods_name: "",
        goods_price: "",
        goods_weight: "",
        goods_number: "",
        //商品分类
        goods_cat: [],
        //上传图片
        pics: [],
        //富文本
        goods_introduce: "",
        attrs: []
      },
      //基本信息表单里的验证规则
      addFormRules: {
        goods_name: [
          { required: true, message: "请输入名称", trigger: "blur" }
        ],
        goods_price: [
          { required: true, message: "请输入价格", trigger: "blur" }
        ],
        goods_weight: [
          { required: true, message: "请输入重量", trigger: "blur" }
        ],
        goods_number: [
          { required: true, message: "请输入数量", trigger: "blur" }
        ],
        goods_cat: [
          { required: true, message: "请选择商品分类", trigger: "blur" }
        ]
      },
      //级联配置文件
      addProps: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children"
      },

      //存放获取商品列表的数据
      cateList: [],
      //动态参数数据
      manyData: [],
      //静态属性数据
      onlyData: [],
      //图片上传组件的请求对象
      axiosToken: {
        Authorization: window.sessionStorage.getItem("token")
      },
      //图片临时路径
      urlPath: "",
      //控制放大图片的显示
      dialogVisiblePreview: false
    };
  },
  created() {
    this.getCateList();
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get("categories");
      if (res.meta.status !== 200) {
        return this.$message.error("获取商品列表失败");
      } else {
        this.cateList = res.data;
        this.$message.success("获取商品列表成功");
      }
    },
    //级联点击事件
    handleChange() {
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = [];
      }
    },
    //只有当级联的数组长度等于3和才会切换Tabs栏
    beforeleavetab(activeName, oldActiveName) {
      if (this.addForm.goods_cat.length !== 3 && oldActiveName === "0") {
        this.$message.error("请选择商品分类");
        return false;
      }
    },
    //点击商品参数，获取动态参数many数据
    async tabClick() {
      if (this.index === "1") {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: "many" }
          }
        );
        if (res.meta.status !== 200) {
          return;
        } else {
          console.log(res.data);
          res.data.forEach(item => {
            item.attr_vals =
              item.attr_vals.length === 0 ? [] : item.attr_vals.split(",");
          });
          this.manyData = res.data;
        }
      } else if (this.index === "2") {
        //点击商品参数，获取静态属性only数据
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: "only" }
          }
        );
        if (res.meta.status !== 200) {
          return;
        } else {
          console.log(res.data);

          this.onlyData = res.data;
        }
      }
    }, //监听上传图片成功
    uploadSuccess(response) {
      console.log(response);
      //1得到图片上传信息对象 临时路径tmp_path
      const tmpPath = { pic: response.data.tmp_path };
      //2 把临时路径对象push到pics数组中
      this.addForm.pics.push(tmpPath);
      console.log(this.addForm);
    },

    //监听点击放大图片浏览
    handlePreview(file) {
      console.log(file);
      this.urlPath = file.response.data.url;
      this.dialogVisiblePreview = true;
    },
    //点击删除上传的图片
    handleRemove(file) {
      console.log(file);
      const path = file.response.data.tmp_path;
      const i = this.addForm.pics.findIndex(x => x.pics === path);
      this.addForm.pics.splice(i, 1);
      console.log(this.addForm);
    },
    //调用API发起添加商品请求
    addGoods() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) {
          return this.$message.error("请填写必要的表单项");
        } else {
          //先把attr里面的数组转换成字符串，使用深度拷贝来接受数据
          const form = _.cloneDeep(this.addForm);
          form.goods_cat = this.addForm.goods_cat.join(",");
          //然后把manyData和onlyData转换成字符串
          this.manyData.forEach(item => {
            const newInfo = {
              attr_id: item.attr_id,
              attr_value: item.attr_vals.join(",")
            };
            this.addForm.attrs.push(newInfo);
          });
          this.onlyData.forEach(item => {
            const newInfo = {
              attr_id: item.attr_id,
              attr_value: item.attr_vals
            };
            this.addForm.attrs.push(newInfo);
          });
          form.attrs = this.addForm.attrs;
          console.log(form);
          //发起添加商品请求
          const { data: res } = await this.$http.post("goods", form);
          if (res.meta.status !== 201) {
            return this.$message.error("添加商品失败");
          } else {
            this.$message.success("添加商品成功");
            this.$router.push("/goods");
          }
        }
      });
    }
  },
  computed: {
    //获取动态参数的请求ID
    cateId() {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2];
      }
    }
  }
};
</script>

<style lang="less" scoped>
.Step {
  margin: 20px 0;
}
.checkbox {
  margin: 0 15px 0 0 !important;
}
.imgWidth {
  width: 100%;
}
</style>